<template>
  <view class="sign-name">
    <view ref="canvasContent" class="canvas-content">
      <canvas ref="canvas" id="canvas" canvas-id="canvas" v-if="canvasSize" :width="canvasSize.width" :height="canvasSize.height" :style="{ width: canvasSize.width + 'px', height: canvasSize.height + 'px' }" @touchstart="drawStart" @touchend="drawEnd" @touchmove="move" />
    </view>
    <view class="btn-content">
      <button @click="clear"><span>清</span><span>除</span></button>
    </view>
  </view>
</template>

<script>
  export default {
    name: 'SignName',
    components: {},
    props: {},
    data() {
      return {
        canvasSize: null,
        ctx: null,
        isDraw: false,
        startPointObj: {
          x: 0,
          y: 0,
        },
        imgUrl: '',
      };
    },
    mounted() {
      this.$nextTick(() => {
        this.setCanvasSize();
        this.createCanvas();
      });
    },
    created() {
      document.body.addEventListener('touchmove', this.stopPageMove, { passive: false });
    },
    beforeDestroy() {
      document.body.removeEventListener('touchmove', this.stopPageMove);
    },
    methods: {
      setCanvasSize() {
        setTimeout(() => {
          const el = this.$refs.canvasContent;
          this.canvasSize = {
            width: el.$el.clientWidth,
            height: el.$el.clientHeight,
          };
        }, 1000);
      },
      createCanvas() {
        this.$nextTick(() => {
          this.ctx = uni.createCanvasContext('canvas', this);
        });
      },
      drawStart(e) {
        if (!this.ctx) {
          return;
        }
        // console.log(e, this.ctx);
        this.ctx.lineWidth = 4;
        this.ctx.lineCap = 'round';
        // this.ctx.lineJoin = 'round';
        this.ctx.strokeStyle = '#000000';
        this.startPointObj = e.touches[ 0 ];
        this.isDraw = true;
      },
      drawEnd(e) {
        if (!this.ctx) {
          return;
        }
        this.isDraw = false;
        // console.log(e);
      },
      move(e) {
        e.preventDefault();
        const { startPointObj, ctx, isDraw } = this;
        if (!(ctx && isDraw)) {
          return;
        }
        const point = e.touches[ 0 ];
        ctx.beginPath();
        ctx.moveTo(startPointObj.x, startPointObj.y);
        ctx.lineTo(point.x, point.y);
        ctx.stroke();
        ctx.closePath();
        ctx.draw(true);
        this.startPointObj = point;
      },
      clear() {
        const { canvasSize, ctx } = this;
        ctx.clearRect(0, 0, canvasSize.width, canvasSize.height);
        ctx.draw(true);
      },
      async getFile() {
        const that = this;
        return new Promise((resolved, rejected) => {
          uni.canvasToTempFilePath({
            canvasId: 'canvas',
            success(res) {
              const { blob, data, file } = that.baseToFile(res.tempFilePath);
              resolved({ file });
            },
            fail() {
              rejected();
            },
          });
        });
      },
      baseToFile(data) {
        const arr = data.split(',');
        const mime = arr[ 0 ].match(/:(.*?);/)[ 1 ];
        const suffix = mime.split('/')[ 1 ];
        const bstr = atob(arr[ 1 ]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        const now = new Date();
        const fileName = `签名${now.valueOf()}`;
        while (n--) {
          u8arr[ n ] = bstr.charCodeAt(n);
        }
        const file = new File([ u8arr ], `${fileName}.${suffix}`, { type: mime });
        const blob = new Blob([ u8arr ], { type: mime });
        // console.log(file, blob);
        return { data, file, blob };
      },
      stopPageMove(e) {
        e.preventDefault();
        e.stopPropagation();
      },
    },
  };
</script>

<style lang="less" scoped>
  .sign-name {
    &, * {
      box-sizing: border-box;
    }
    position: relative;
    height: 100%;
    .canvas-content {
      height: 100%;
    }
    .btn-content {
      position: absolute;
      bottom: 10px;
      right: 10px;
      z-index: 10;
      button {
        font-size: 12px;
        background-color: white;
        line-height: 1;
        padding: 10px;
      }
    }
  }
</style>
